package com.gzs.learn.springcloud.aspect;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author zhisong.guan
 */
@Aspect
@Component
@Slf4j
public class ServiceAspect {
    private static final String BASE_PACKAGE = "com.gzs.learn.springcloud";
    private static final String SERVICE_POINT = "execution(public * " + BASE_PACKAGE + ".*.service..*.*(..))";

    @Around(SERVICE_POINT)
    public Object logRestController(ProceedingJoinPoint point) throws Throwable {
        return logSystemError(point);
    }

    private Object logSystemError(ProceedingJoinPoint point) throws Throwable {
        Object ret;
        Stopwatch stopwatch = Stopwatch.createStarted();
        String clzName = "";
        String methodName = "";
        try {
            MethodSignature sig = (MethodSignature) point.getSignature();
            Object target = point.getTarget();
            Method currentMethod = target.getClass().getMethod(sig.getName(), sig.getParameterTypes());
            clzName = sig.getDeclaringTypeName();
            methodName = currentMethod.getName();
            ret = point.proceed();
            return ret;
        } catch (Exception e) {
            log.error("occur sys exception ", e);
            throw e;
        } finally {
            stopwatch.stop();
            log.info("class [{}] method [{}] cost [{}]", clzName, methodName, stopwatch);
        }
    }
}
